package cn.shadow.service;

import cn.shadow.bean.PlayerModule;
import cn.shadow.entity.ConnectedUser;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * 管理所有连接的用户
 */
@Component
@Data
@Slf4j
public class WorldService implements ApplicationContextAware {

    private final Map<Long, ConnectedUser> userMap;
    @Autowired
    Services services;
    public WorldService() {
        userMap = new ConcurrentHashMap<>();
    }

    /**
     * 添加连接用户
     */
    public ConnectedUser addConnectedUser(ConnectedUser user) {
        return userMap.putIfAbsent(user.getUserId(), user);
    }

    /**
     * 移除连接用户
     */
    public boolean removeUser(ConnectedUser user) {
        return userMap.remove(user.getUserId()) != null;
    }

    /**
     * 通过id获取连接用户
     */
    public ConnectedUser getUser(long userId) {
        return userMap.get(userId);
    }

    /**
     * 获得玩家对象
     */
    public PlayerModule getPlayerModule(long userId) {
        ConnectedUser user = getUser(userId);
        if (user == null) {
            return null;
        }
        return user.getPlayerModule();
    }

    /**
     * 获取在线人数
     */
    public int getOnLineCount() {
        return userMap.size();
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        ScheduledExecutorService service = services.getIThreadService().getScheduledExecutorService();
        service.scheduleAtFixedRate(() -> log.info("在线人数：" + getOnLineCount()), 10, 30, TimeUnit.SECONDS);
    }
}
